package com.zhiyinlou.api.listener;


import java.util.Iterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import com.zhiyinlou.api.testcase.base.BaseCase;

public class TestngListener extends TestListenerAdapter {

	private static Logger logger = LogManager.getLogger(TestngListener.class);
	


	@Override
	public void onTestFailure(ITestResult tr) {
		super.onTestFailure(tr);
		Throwable throwable = tr.getThrowable();

		if (null != throwable) {
			String throwableName = throwable.getClass().getName();
			if (null != throwableName) {
				logger.error(throwableName);
			}
		}

		BaseCase.resultsMap.put(tr.getStartMillis(), tr.getStatus());
		logger.error(tr.getInstanceName() + " : " + tr.getName() + " Failure...");
	
		
	}

	@Override
	public void onTestSkipped(ITestResult tr) {
		String trName = tr.getName();
		
		if (trName.equals("comment")) {
			return;
		}
		
		super.onTestSkipped(tr);
		BaseCase.resultsMap.put(tr.getStartMillis(), tr.getStatus());
		logger.info(tr.getInstanceName() + " : " + trName + " Skipped...");
		
	}

	@Override
	public void onTestSuccess(ITestResult tr) {
		super.onTestSuccess(tr);
		BaseCase.resultsMap.put(tr.getStartMillis(), tr.getStatus());
		logger.info(tr.getInstanceName() + " : " + tr.getName() + " Success...");
		
	}

	@Override
	public void onTestStart(ITestResult tr) {
		super.onTestStart(tr);
		logger.info(tr.getInstanceName() + " : " + tr.getName() + " Start...");
	}

	@Override
	public void onFinish(ITestContext testContext) {
		Iterator<ITestResult> listOfFailedTests = testContext.getFailedTests().getAllResults().iterator();
		
		while (listOfFailedTests.hasNext()) {
			ITestResult failedTest = listOfFailedTests.next();
			ITestNGMethod method = failedTest.getMethod();
			if (testContext.getFailedTests().getResults(method).size() > 1) {
				listOfFailedTests.remove();
			} else {
				if (testContext.getPassedTests().getResults(method).size() > 0) {
					listOfFailedTests.remove();
				}
			}
		}
	}

	
	
}
